package com.liuweiheng.cloudproviderpayment8002.config;

import com.liuweiheng.cloudproviderpayment8002.shiro.cache.RedisCacheManager;
import com.liuweiheng.cloudproviderpayment8002.shiro.realm.CustomerRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * Springboot-Shiro配置类
 *
 * @author lwh
 */
@Configuration
public class ShiroConfig {


    /**
     * ShiroFilter
     * 负责拦截所有请求
     * @param defaultWebSecurityManager 安全管理器
     * @return 拦截器
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        // 给filter设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        /**
         * anon：无需认证
         * authc：必须认证
         * user：必须拥有 记住我 功能才使用
         * perms：拥有对某个资源的权限才能访问
         * roles：拥有某个角色权限才能访问
         */

        // 配置系统的受限资源
//        Map<String, String> map = new HashMap<>(16);
//        map.put("/base/index", "authc");
//        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        // 配置访问失败后的默认访问路径
//        shiroFilterFactoryBean.setLoginUrl("/base/error");

        // 配置系统的公共资源

        return shiroFilterFactoryBean;
    }

    /**
     * SecurityManager
     * @param realm 自定义realm
     * @return 安全管理器
     */
    @Bean
    public DefaultWebSecurityManager getDefaultSecurityManager(CustomerRealm realm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        // 设置自定义Realm
        defaultWebSecurityManager.setRealm(realm);

        return defaultWebSecurityManager;
    }

    /**
     * 自定义Realm
     */
    @Bean
    public CustomerRealm getCustomerRealm() {
        CustomerRealm realm = new CustomerRealm();
        // 创建hash凭证匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        // 设置匹配器使用md5进行加密
        credentialsMatcher.setHashAlgorithmName("md5");
        // 设置加密散列次数
        credentialsMatcher.setHashIterations(1024);
        // 设置realm中的凭证匹配器
        realm.setCredentialsMatcher(credentialsMatcher);

        // 开启缓存管理
        realm.setCacheManager(new RedisCacheManager());
        realm.setCachingEnabled(true);
        realm.setAuthenticationCachingEnabled(true);
        realm.setAuthenticationCacheName("authenticationCache");
        realm.setAuthorizationCachingEnabled(true);
        realm.setAuthorizationCacheName("authorizationCache");


        return realm;
    }

}
